package xyz.xtgl.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import plus.handler.LogicMetaObjectHandler;
import plus.handler.LogicMetaObjectHandlerService;
import xyz.xtgl.config.helper.MyCustomUserDetails;
import xyz.xtgl.erp.system.entity.SysUser;

/**
 * @author liubo
 * @created 2020-02-03 11:57
 */
@Configuration
public class DatabaseConfig {

    /**
     * 获取登录用户
     * @return
     */
    @Bean
    public LogicMetaObjectHandlerService logicMetaObjectHandlerService(){
        return new LogicMetaObjectHandlerService(){
            @Override
            public String getOperator() {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if(authentication instanceof UsernamePasswordAuthenticationToken) {
                    SysUser user = ((MyCustomUserDetails) authentication.getPrincipal()).getData();
                    return user.getPhone();
                }
                return "system";
            }
        };
    }

    /**
     * 自动填充
     * @return
     */
    @Bean
    public MetaObjectHandler metaObjectHandler(){
        return new LogicMetaObjectHandler(logicMetaObjectHandlerService());
    }

    /**
     * 分页转换
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }

    /**
     * 乐观锁
     * @return
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}
